//app.js
App({
  globalData: {
    //用户key缓存
    userInfoKey: 'userInfoKey',
    userInfo: {
      NickName: '',
      Sex: '',
      City: '',
      Province: '',
      Country: '',
      HeadImgUrl: '',
      Language: '',
      AuthCode: '',
      OpenID: "",
      UnionID: "",
      UserMobile: '',
      UserId: 0,
      WeChartUserID: 0
    },
    authCode: '', //授权码
    baseUrl: 'https://dev.banmachewu.com/youweiapi/api/'
  },
  onLaunch: function() {},
  onShow: function(options) {
    let self = this;
    self.globalData.shareTicket = options.shareTicket;
    if (options.shareTicket) {
      console.log('shareTicket', options.shareTicket);
      wx.getShareInfo({
        // 把票据带上
        shareTicket: options.shareTicket,
        success: function(res) {
          console.log('信息', res);
        }
      })
    }
  },
  //请求用户微信信息
  requestUserWxInfo: function() {
    let self = this;
    wx.getSetting({
      success: function(t) {
        console.log("t:" + t)
        t.authSetting["scope.userInfo"] ? wx.getUserInfo({
          lang: "zh_CN",
          success: function(t) {
            self.sendUserInfo(t.userInfo);
          },
          fail: function(t) {
            console.log("getUserInfo fail");
          }
        }) : self.getAppCurrentPage().setData({
          showGetUserInfo: true
        });
      },
      fail: function(t) {
        self.getAppCurrentPage().setData({
          showGetUserInfo: true
        });
      }
    });
  },
  //获取当前页
  getAppCurrentPage: function() {
    let e = getCurrentPages();
    return e[e.length - 1];
  },
  //发送用户信息到后台
  sendUserInfo: function(usr) {
    let self = this;
    // 登录
    wx.login({
      success: (res) => {
        console.log(res)
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        if (res.errMsg == "login:ok") {
          self.globalData.userInfo = {
            NickName: usr.nickName,
            Sex: usr.gender,
            City: usr.city,
            Province: usr.province,
            Country: usr.country,
            HeadImgUrl: usr.avatarUrl,
            Language: usr.language,
            AuthCode: res.code
          };

          self.sendRequest({
            url: self.globalData.baseUrl + "WxUser/AddOrUpdate",
            method: "POST",
            data: self.globalData.userInfo,
            success: function(res) {
              console.log('res', res);
              let rdata = res.data;
              if (rdata.status == 0 && rdata.data) {
                //wx.hideLoading();
                self.globalData.userInfo.OpenID = rdata.data.OpenID;
                self.globalData.userInfo.UnionID = rdata.data.UnionID;
                self.globalData.userInfo.WeChartUserID = rdata.data.WeChartUserID;
                self.setUserInfo();
              } else {
                wx.showToast({
                  title: rdata.message,
                  icon: 'none'
                })
              }
            },
            fail: function(e) {

            }
          });
        }
      }
    });
  },
  //发送请求
  sendRequest: function(opts) {
    let self = this;
    opts.showLoading ? wx.showLoading({
      content: '加载中...',
      delay: 0,
    }) : '';
    //添加headers
    if (opts.header) {} else {
      opts.header = {};
    }
    opts.header['Content-Type'] = 'application/json';
    for (let k in self.cltInfo) {
      opts.header[k] = self.cltInfo[k]
    }
    //错误提示
    if (opts.fail) {} else {
      wx.hideLoading();
      //如果错误添加错误日志
      opts.fail = function(res) {
        //暂时没有
      }
    }

    //微信小程序post参数必须,解析成字符串,官方标准解答
    if (opts.data) {
      if (opts.method == "POST" || opts.method == "post") {
        opts.data = JSON.stringify(opts.data);
      }
    }
    if (opts.complete) {} else {
      opts.complete = function(res) {
        if (opts.showLoading === false) {} else {
          wx.hideLoading();
        }
      }
    }
    wx.request(opts);
  },
  //设置用户信息
  setUserInfo: function() {
    let self = this;
    wx.setStorage({
      key: self.globalData.userInfoKey,
      data: JSON.stringify(self.globalData.userInfo)
    });
  },
  //获取用户信息
  getUserInfo: function() {
    let self = this;
    let usr = wx.getStorageSync(self.globalData.userInfoKey);
    if (usr) {
      self.globalData.userInfo = JSON.parse(usr);
    }
    return self.globalData.userInfo;
  }
})